/*
 * Copyright (c) 2015 MONKEYK Information Technology Co. Ltd
 * www.monkeyk.com
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * MONKEYK Information Technology Co. Ltd ("Confidential Information").
 * You shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement you
 * entered into with MONKEYK Information Technology Co. Ltd.
 */
package com.youxin.third.auth.oauth2.service;


import com.youxin.third.auth.model.AccessToken;
import com.youxin.third.auth.model.ClientDetails;
import com.youxin.third.auth.service.manager.OAuthManager;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuer;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.util.Date;

/**
 * 2015/10/22
 *
 * @author Shengzhao Li
 */
public abstract class AbstractAccessTokenHandler extends AbstractOAuthHolder {

    private static final Logger LOG = LoggerFactory.getLogger(AbstractAccessTokenHandler.class);


    protected OAuthManager oAuthManager;


    protected transient AuthenticationIdGenerator authenticationIdGenerator;


    protected OAuthIssuer oAuthIssuer;

    public OAuthManager getoAuthManager() {
        return oAuthManager;
    }

    public void setoAuthManager(OAuthManager oAuthManager) {
        this.oAuthManager = oAuthManager;
    }

    public AuthenticationIdGenerator getAuthenticationIdGenerator() {
        return authenticationIdGenerator;
    }

    public void setAuthenticationIdGenerator(AuthenticationIdGenerator authenticationIdGenerator) {
        this.authenticationIdGenerator = authenticationIdGenerator;
    }

    public OAuthIssuer getoAuthIssuer() {
        return oAuthIssuer;
    }

    public void setoAuthIssuer(OAuthIssuer oAuthIssuer) {
        this.oAuthIssuer = oAuthIssuer;
    }

    protected AccessToken createAndSaveAccessToken(ClientDetails clientDetails, boolean includeRefreshToken, String username, String authenticationId) throws OAuthSystemException {
        Assert.notNull(username, "username is null");
        AccessToken accessToken = new AccessToken();
        accessToken.setClientId(clientDetails.getClientId());
        accessToken.setUsername(username);
        accessToken.setTokenId(oAuthIssuer.accessToken());
        accessToken.setAuthenticationId(authenticationId);
        accessToken.setCreateTime(new Date());
        accessToken.updateByClientDetails(clientDetails);

        if (includeRefreshToken) {
            accessToken.setRefreshToken(oAuthIssuer.refreshToken());
        }

        oAuthManager.saveAccessToken(accessToken);
        LOG.debug("Save AccessToken: {}", accessToken);
        return accessToken;
    }

}
